package com.lagou;/**
 * Created by IntelliJ IDEA.
 * User: Yangdx.
 * Date: 2020/12/14.
 * Time: 2:17.
 * Tags: Code, we are serious.
 */

import com.lagou.mapper.OrderMapper;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.UUID;

/**
 * @author
 * @create 2020-12-14 2:17
 **/
@Service
public class OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;
    /**
     * 生成订单
     */
    public String add() {
        //生成主键订单id
        String orderId = UUID.randomUUID().toString().replace("-", "");
        //订单入库，且状态为未支付；
        OrderVO orderVO = new OrderVO();
        orderVO.setId(orderId);
        orderVO.setStatus("待支付");
        orderMapper.addOrder(orderVO);
        //发送消息到rabbitmq；
        rabbitTemplate.convertAndSend(RabbitMQConfig.ORDER_EXCHANGE, RabbitMQConfig.ORDER_ROUTING_KEY, orderId, messagePostProcessor());
        return orderId;
    }

    /**
     * 根据id支付订单
     */
    public String pay(String id) {
        //获取订单状态
        OrderVO orderVO = orderMapper.getOrderById(id);
        String status = orderVO.getStatus();
        if ("超时未支付".equals(status)) {
            return "超时未支付";
        }
        //更新订单状态为支付成功
        orderVO.setStatus("支付成功");
        orderMapper.updateOrderById(orderVO);
        return "支付成功";
    }

    /**
     * 发送消息处理
     */
    private MessagePostProcessor messagePostProcessor() {
        return new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //设置有效期10秒(正常业务场景一般都为15分钟或者30分钟)
                message.getMessageProperties().setExpiration("10000");
                return message;
            }
        };
    }
}

